package com.yang.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import com.yang.entity.Permissions;
import com.yang.entity.Roles;
import com.yang.entity.User;

public class UserUtils {
	private UserUtils(){}
	/**
	 * 获取当前系统登录的用户
	 * @return
	 */
	public static User getLoginUser(){
		Subject userSubject = SecurityUtils.getSubject();
		return (User) userSubject.getSession().getAttribute("currentUser");
	}
	
	/**
	 * 获取当前登录用户所具有的权限
	 * @return
	 */
	public static List<Permissions> getLoginUserPermissons(){
		User u = getLoginUser();
		List<Permissions> permissions = new ArrayList<Permissions>();
		if(null!=u){
			Set<Roles> roles = u.getRoles();
			if(null!=roles){
				for (Roles role : roles) {
					if(null!=role.getPermissions()){
						for(Permissions permission : role.getPermissions()){
							permissions.add(permission);
						}
					}
				}
			}
			return permissions.isEmpty()?null:permissions;
		}
		return permissions;
	}
	
	/**
	 * 判断当前角色是否具有ALL权限
	 * @param role	当前角色
	 * @return
	 */
	public static boolean isRoleHasAllPermisson(Roles role){
		if(null!=role && null!=role.getPermissions()){
			for(Permissions permission : role.getPermissions()){
				if("ALL".equals(permission.getpCode())){
					return true;
				}
			}
		}
		return false;
	}
	
	/**
	 * 判断当前用户是否具有"ALL"权限，即所有权限
	 * @return
	 */
	public static boolean isAllPermission(){
		User u = getLoginUser();
		if(null!=u){
			Set<Roles> roles = u.getRoles();
			if(null!=roles){
				for (Roles role : roles) {
					if(null!=role.getPermissions()){
						for(Permissions permission : role.getPermissions()){
							if("ALL".equals(permission.getpCode())){
								return true;
							}
						}
					}
				}
			}
		}
		return false;
	}
}
